<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="数据权限"
    width="50%"
    @ok="closeDrawer()"
  >
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleAdd">新增规则</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              onClick: handleEdit.bind(null, record),
              label: t('编辑'),
            },
          ]"
        />
      </template>
    </BasicTable>
    <EditDataScopeDrawer @register="registerEditDrawer" @success="handleEditSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { dataScopeColumns, dataScopeSearchFormSchema } from '../menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import EditDataScopeDrawer from './EditDrawer.vue';
  import { list } from '@/api/sys/sysDataScopeManage';
  import { useDrawer } from '@/components/Drawer';
  import { useI18n } from '@/hooks/web/useI18n';
  const emits = defineEmits([ 'register' ]);
  const { t } = useI18n();
  let menuRecord = ref<Recordable>({});
  // 编辑抽屉
  const [registerEditDrawer, { openDrawer: openEditDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    title: t('权限列表'),
    api: list,
    columns: dataScopeColumns,
    formConfig: {
      labelWidth: 120,
      schemas: dataScopeSearchFormSchema,
    },
    striped: false,
    useSearchForm: true,
    pagination: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    beforeFetch: (params: Recordable) => {
      params.menuId = menuRecord.value.id;
      return params;
    },
    actionColumn: {
      width: 120,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    fixed: 'right',
    },
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false });
    menuRecord.value = data.record;
    reload();
  });

  const handleAdd = () => {
    openEditDrawer(true, {
      menuId: menuRecord.value.id,
      isUpdate: false,
    });
  };
  const handleEdit = (record: Recordable) => {
    openEditDrawer(true, {
      menuId: menuRecord.value.id,
      record,
      isUpdate: true,
    });
  };
  const handleEditSuccess = () => {
    reload();
  };
</script>
